<?php include 'assets/tool/01_function.php'; ?>
<?php
class ArticleController extends AdminController
{
/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array("index","list","listdetail","edit","delete","save","UploadImage"),
			    "users" => array("@"),
				"expression" => "Yii::app()->user->authority == Account::ADMIN"
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			)
		);
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->render("index");
	}
	
	public function actionList()
	{
		$this->renderPartial("list");
	}
	
	public function actionListdetail()
	{
		//$dataProvider=new CActiveDataProvider('Index');
		$i_amountPerPage	= $_REQUEST["amountPerPage"];
		$i_page				= $_REQUEST["page"];
		$s_filter 			= $_REQUEST["txt_filter"];
		$s_columnName 		= $_REQUEST["columnName"];
		$s_sortMethod 		= $_REQUEST["sortMethod"];
		
		//prepare where statement
		//art.`title` LIKE '%".$s_filter."%' OR
		//art.`description` LIKE '%".$s_filter."%' 
		$s_where = "1";
		//prepare order statement
		$s_order = "`".$s_columnName."` ".$s_sortMethod;
		
		$i_total = Yii::app()->db->createCommand("Select Count(*) from `article` art where ".$s_where.";")->queryScalar();;
		
		$arr_model = $this->getAllList($i_page, $i_amountPerPage, $s_order, $s_where);
		
		$this->renderPartial(
			"listdetail",
			array(
				"arr_data"			=> $arr_model,
				"i_totalItem"		=> $i_total,
				"i_amountPerPage"	=> $i_amountPerPage,
				"i_currentPage"		=> $i_page
			)
		);
	}
	
	public function actionEdit()
	{
		$dataProvider=new CActiveDataProvider("ArticleCategory");
		
		if(isset($_POST["i_key"]) && $_POST["i_key"] > 0)
		{
			$model=$this->loadModel($_POST["i_key"]);

			$this->renderPartial(
				"edit",
				array(
					"o_model"=>$model,
					"i_key"=>$_POST["i_key"],
					"arr_data"=>$dataProvider->data
				)
			);
		}
		else 
			$this->renderPartial(
				"edit",
				array(
					"i_key"=>0,
					"arr_data"=>$dataProvider->data
				)
			);
	}
	
	public function actionSave()
	{
		$date_approval = null;
		if( isset($_REQUEST["chk_approval"]) && $_REQUEST["chk_approval"] == 1) {
			$date_approval = new DateTime();
			$date_approval = $date_approval->format("Y-m-d");
		}
		
		//Add record
		if( isset($_REQUEST["item_key"]) && $_REQUEST["item_key"] == 0)
		{
			$command = Yii::app()->db->createCommand("CALL article_03_insert
			(
				:p_category,
				:p_title,
				:p_image,
				:p_content,
				:p_tag,
				:p_approval,
				:p_approval_date,
				:p_url,
				:p_desc
			)");
			  
			$command->bindValue("p_category", $_REQUEST["sl_category"],PDO::PARAM_INT);
			$command->bindValue("p_title", CHtml::encode($_REQUEST["txt_title"]));
			$command->bindValue("p_image",$_REQUEST["txt_image"]);
			$command->bindValue("p_content",CHtml::encode($_REQUEST["ta_content"]));
			$command->bindValue("p_tag",$_REQUEST["txt_tag"]);
			$command->bindValue("p_approval",$_REQUEST["chk_approval"],PDO::PARAM_INT);
			$command->bindValue("p_approval_date",$date_approval);
			$command->bindValue("p_url",$_REQUEST["txt_urlMapping"]);
			$command->bindValue("p_desc",CHtml::encode($_REQUEST["ta_description"]));
			
			try
			{
				$i_result = $command->execute();
				if($i_result >=1)
				{
					$arr_result = array("result" => 1);
	    			exit(json_encode($arr_result));
				}
				else
				{
					$arr_result = array("error" => "Có lỗi trong quá trình thêm mới, vui lòng thử lại sau.");
    				exit(json_encode($arr_result));
				}
			}
			catch (CDbException $ex)
			{
				$arr_result = array("error" => $ex->getMessage());
    			exit(json_encode($arr_result));
			}			
		}//End if add record
		//Update record
		else
		{
			$command = Yii::app()->db->createCommand("CALL article_04_update
			(
				:p_key,
				:p_category,
				:p_title,
				:p_image,
				:p_content,
				:p_tag,
				:p_approval,
				:p_approval_date,
				:p_url,
				:p_desc
			)");
			
			$command->bindValue("p_key",$_REQUEST["item_key"]);
			$command->bindValue("p_category", $_REQUEST["sl_category"],PDO::PARAM_INT);
			$command->bindValue("p_title", CHtml::encode($_REQUEST["txt_title"]));
			$command->bindValue("p_image",$_REQUEST["txt_image"]);
			$command->bindValue("p_content",CHtml::encode($_REQUEST["ta_content"]));
			$command->bindValue("p_tag",$_REQUEST["txt_tag"]);
			$command->bindValue("p_approval",$_REQUEST["chk_approval"],PDO::PARAM_INT);
			$command->bindValue("p_approval_date",$date_approval);
			$command->bindValue("p_url",$_REQUEST["txt_urlMapping"]);
			$command->bindValue("p_desc",CHtml::encode($_REQUEST["ta_description"]));
			
			try
			{
				$row = $command->queryRow();
				if($row !=null)
				{
					$m_model = new Article();
					$m_model->unsetAttributes();
					
					$d_insert = new DateTime($row["insert"]);
				
					$m_model->key = $row["identification"];
					$m_model->title = $row["title"];
					$m_model->category_name = $row["category_name"];
					$m_model->description = $row["description"];
					$m_model->tag = $row["tag"];
					$m_model->insert = $d_insert->format("Y-m-d");

	    			exit(json_encode($m_model->getAttributes(array("key","title","category_name","description","tag","insert"))));
				}
				else
				{
					$arr_result = array("error" => "Có lỗi trong quá trình cập nhật, vui lòng thử lại sau.");
    				exit(json_encode($arr_result));
				}
			}
			catch (CDbException $ex)
			{
				$arr_result = array("error" => $ex->getMessage());
    			exit(json_encode($arr_result));
			}
		}//End else
		Yii::app()->end();
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		//$this->loadModel($id)->delete();
		$arr_deleteId 	= $_REQUEST["arr_deleteId"];
    	
    	if(is_array($arr_deleteId) == true) {
    	
    		$s_where		= "";
    		
    		foreach ($arr_deleteId as $value) {
    			$s_where .= "`identification` = ".$value["value"]." OR ";
    		}
    	
    		$s_where	= substr($s_where, 0, -3);
    		
			$command = Yii::app()->db->createCommand("CALL article_05_delete (:in_where)");  
			$command->bindValue("in_where",$s_where);
			$s_result = $command->execute(); 
    		
    		if( $s_result >= 0) {
    			
    			$arr_result = array("result" => $s_result);
    			exit(json_encode($arr_result));
    		}
    		else {
    			
    			$arr_error = array("error" => "Đã có lỗi với quá trình xoá, xin hãy nhấn F5 để thử lại:".$s_result);
    			exit(json_encode($arr_error));
    		}
    	
    	} else {
    		
    		$arr_error = array("error" => "Bạn phải chọn một dòng để xoá.");
    		exit(json_encode($arr_error));
    	}
	}
	
	
	public function actionUploadImage()
    {
    	$o_fileInputName = $_REQUEST["fileInputName"];
    	$s_destinationFolder = $_REQUEST["url_image"];
    	$i_width = $_REQUEST["width_image"];
    	$i_height = $_REQUEST["height_image"];
    	
    	$arr_types = Array("image/png", "image/gif", "image/jpeg");
    	
    	$arr_result =  uploadImageAjax($arr_types, $o_fileInputName, $s_destinationFolder, $i_width, $i_height);
    	 
    	if( is_array($arr_result) == true)
    	{
    		exit(json_encode($arr_result));
    	}
    	else
    	{
    		$arr_result = array("result" => $arr_result);
    		exit(json_encode($arr_result));
    	}
    	Yii::app()->end();
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Account the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Article::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	protected function getAllList($i_page,$i_amountPerPage,$s_order,$s_where) {
		
		$command = Yii::app()->db->createCommand("CALL article_01_getList(:p_page,:p_amount,:p_oder,:p_where)");  
		$command->bindValue("p_page",$i_page);
		$command->bindValue("p_amount",$i_amountPerPage);
		$command->bindValue("p_oder",$s_order);
		$command->bindValue("p_where",$s_where);
		echo $s_where;
		$arr_model = array();
		$arr_data = $command->queryAll();
		
		foreach ( $arr_data as $key => $row) {
			$m_model = new Article();
			$m_model->unsetAttributes();
		
			$m_model->identification = $row["identification"];
			$m_model->key = $row["identification"];
			$m_model->article_category = $row["article_category"];
			$m_model->category_name = $row["category_name"];
			$m_model->title = $row["title"];
			$m_model->url_mapping = $row["url_mapping"];
			$m_model->image = $row["image"];
			$m_model->description = $row["description"];
			$m_model->content= $row["content"];
			$m_model->tag = $row["tag"];
			$m_model->approval = $row["approval"];
			$m_model->approval_date = $row["approval_date"];
			$m_model->note = $row["note"];
			$m_model->insert = $row["insert"];
			$m_model->update = $row["update"];
			$m_model->delete = $row["delete"];
			
			array_push($arr_model, $m_model);
		}//End foreach
		
		return $arr_model;
	}
}